﻿using BasicInformation.ApiRead.Application.Command.Supplier;
using BasicInformation.Domain;
using BasicInformation.Dtos;
using BasicInformation.ErrorCode;
using BasicInformation.Infrastructure.Implement;
using Dapper;
using MediatR;
using Org.BouncyCastle.Asn1.X509;
using System.Collections.Generic;
using System.Drawing;
using System.Text;

namespace BasicInformation.ApiRead.Application.Handler.Supplier
{
    public class GetSupplierHandler : IRequestHandler<GetSupplierCommand, ApiPaging<SupplierDTO>>
    {
        private readonly DatabaseContext db;
        private readonly ILogger<GetSupplierHandler> logger;

        public GetSupplierHandler(DatabaseContext db,ILogger<GetSupplierHandler> logger)
        {
            this.db = db;
            this.logger = logger;
        }
        public async Task<ApiPaging<SupplierDTO>> Handle(GetSupplierCommand request, CancellationToken cancellationToken)
        {
            ApiPaging<SupplierDTO> result= new ApiPaging<SupplierDTO>();
            StringBuilder sql= new StringBuilder();
            StringBuilder countSql= new StringBuilder();

            sql.Append(@"SELECT
	            s.SupplierId,
	            s.SupplierCode,
	            s.SupplierName,
	            s.SupplierTel,
	            s.SupplierContact,
	            s.SupplierAddr,
	            s.SupplierRemark,
	            s.STyprId,

	            st.STypeName,
	            s.CreatTime,
	            s.Fax,
	            s.Email
	
            FROM
	            suppliermodel s
	            JOIN suppliertypemodel st ON s.STyprId = st.STypeId 
            WHERE
	            IsDel = 0");
            countSql.Append(@"SELECT COUNT(*) FROM suppliermodel");
            if (!string.IsNullOrEmpty(request.SupplierCode))
            {
                sql.Append(" AND s.SupplierCode = @SupplierCode");
            }

            if (!string.IsNullOrEmpty(request.SupplierName))
            {
                sql.Append(" AND s.SupplierName LIKE @SupplierName");
            }
            if (request.STyprId>0)
            {
                sql.Append(" AND s.STyprId = @STyprId");
            }
            if (!string.IsNullOrEmpty(request.SupplierTel))
            {
                sql.Append(" AND s.SupplierTel LIKE @SupplierTel");
            }
            sql.Append(" ORDER BY s.CreatTime DESC LIMIT @size OFFSET @offset");
            var parameters = new
            {
                SupplierCode=request.SupplierCode,
                SupplierName = string.IsNullOrEmpty(request.SupplierName) ? null : $"%{request.SupplierName}%",
                STyprId=request.STyprId,
                SupplierTel = string.IsNullOrEmpty(request.SupplierTel) ? null : $"%{request.SupplierTel}%",
                offset=(request.index-1)*request.size,
                size=request.size,
            };
            try
            {
                // 执行查询
                var pageData = await db.DapperConnection.QueryAsync<SupplierDTO>(sql.ToString(), parameters);
                //执行总页查询
                int totalCount = await db.DapperConnection.ExecuteScalarAsync<int>(countSql.ToString(), parameters);
                //计算总页数
                int totalPage = (int)Math.Ceiling(totalCount / (double)request.size);

                // 设置返回结果
                result.Msg = "供应商管理查询成功";
                result.Code = ApiEnum.OK;
                result.Data = pageData.ToList();
                result.TotalCount = totalCount;
                result.TotalPCount = totalPage;
            }
            catch (Exception ex)
            {
                logger.LogError(ex, "查询供应商信息时发生错误");
                result.Msg = "查询供应商信息时发生错误";
                result.Code = ApiEnum.Fail;
            }
            return await Task.FromResult(result);
        }
    }
}
